/*
Kakine
ActionScript Framework
Copyright © 2011, PUNY, LLC.

This file is part of KAKINE.

KAKINE is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

KAKINE is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with KAKINE.  If not, see <http://www.gnu.org/licenses/>.
*/ 
package com.puny.mvc.controllers.rope
{
	import com.puny.mvc.controllers.Controller;
	import com.puny.mvc.views.rope.RopeParticle;

	public class RopeController extends Controller
	{
//		[Embed(source="star.swf")]
//		private var swf:Class;

		private var _pts:Array = [];
		private var _firstPt:RopeParticle = null;
		private var _tension:uint = 1;
		protected var _first:Boolean = true;
//		private var _cls:ButtonView;
		public function RopeController()
		{
			super();
		}

		protected function createRope(n:uint):void {
			for(var i:int = 0;i < n;i++) {
				_pts.push(new RopeParticle());
			}
			for(var index:int = 0;index < _pts.length;index++) {
				if (index < _pts.length - 1) {
					_pts[index].connection(_pts[index+1]);
				}
				if (index > 0) {
					_pts[index].connection(_pts[index-1]);
				}
			}
		}
//		override protected function setup():void {
//			_cls = new RichButtonView(swf,"next");
//			_cls.addEventListener(ButtonView.CLICKED, nextHandler);
//			addChild(_cls);
//			_cls.x = 80;
//		}
//
//		private function nextHandler(event:Event):void {
//			complete();
//		}
		
		protected function get particles():Array {
			return _pts;
		}
		
		override public function afterReady():void {
			update();
		}
		
		override public function procedureMainFrame():Boolean {
			var energy:Number = 0;
			for (var i:uint = 0;i < _tension;i++) {
				for each(var pt:RopeParticle in _pts) {
					pt.update();
				}
				update();
			}
			return true;
		}
		
		protected function draw(pt:RopeParticle):void {
			if (isFirst) {
				graphics.clear();
				graphics.lineStyle(2,0xFF0000);
				graphics.moveTo(pt["position"].x,pt["position"].y);
			} else {
				graphics.lineTo(pt["position"].x,pt["position"].y);
			}
		}
		
		protected function get isFirst():Boolean {
			return _first;
		}
		
		private function update():void {
			for each(var pt:RopeParticle in _pts) {
				pt.record();
				if (_firstPt == null) {
					_firstPt = pt;
				}
				_first = (pt == _firstPt);
				draw(pt);
			}
		}
		
		protected function set tension(value:uint):void {
			_tension = value;
		}
	}
}